package com.yrh.controller;

import com.yrh.bean.TCategory;
import com.yrh.service.TCategoryService;
import com.yrh.service.impl.TCategoryServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@WebServlet("/CategoryServlet/*")
public class CategoryServlet extends BaseServlet {
    private TCategoryService service=new TCategoryServiceImpl();
    //餐品分类
    public void gotoCategory(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //携带数据回去渲染
        List<TCategory> aList = service.allCategory();
        request.setAttribute("aList",aList);
        request.getRequestDispatcher("/category.jsp").forward(request,response);
    }
    //查询餐品是否存在
    public void cheName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台的参数
        String name = request.getParameter("name");
        TCategory t = service.byName(name);
        if (t!=null){
            response.getWriter().println(1);
        }else {
            response.getWriter().println(-1);
        }
    }
    public void updateCate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台请求参数
        Map<String, String[]> map = request.getParameterMap();
        TCategory t=new TCategory();
        BeanUtils.populate(t,map);
        int i = service.updateCate(t);
        request.getRequestDispatcher("/CategoryServlet/gotoCategory").forward(request,response);
    }
    //删除菜品
    public void del(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取前台请求参数
        Map<String, String[]> map = request.getParameterMap();
        TCategory t=new TCategory();
        BeanUtils.populate(t,map);
        int i = service.delCate(t);
        if (i>0){
            response.getWriter().println(1);
        }else {
            response.getWriter().println(-1);
        }
//        request.getRequestDispatcher("/CategoryServlet/gotoCategory").forward(request,response);
    }
    //添加菜品
    public void addCate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        TCategory t = new TCategory();
        BeanUtils.populate(t, map);
        System.out.println("t = " + t);
        int i = service.addCate(t);
        request.getRequestDispatcher("/CategoryServlet/gotoCategory").forward(request,response);
    }
}
